#!/usr/bin/env bash

SERVER_NAME=mysql
IMAGE_NAME=mysql
VERSION=8.0.36
PORT=3306
MYSQL_ROOT_PASSWORD=ggs2024
DIR=/home/app/$IMAGE_NAME/
if [ -d "./Dockerfile" ];
then
  echo "Find Dockerfile.Will build docker images."
  docker build -t $IMAGE_NAME:$VERSION ./
fi
if [ ! -d "$DIR" ];
then
  mkdir -p $DIR;
  echo "dir $DIR create successful."
else
  echo "dir $DIR already exist.Will use it."
fi
echo "remove old container"

EM_RUN=$(docker ps| grep $SERVER_NAME|awk 'NR==1'|awk '{print $1}')
EM=$(docker ps -a | grep $SERVER_NAME|awk 'NR==1'|awk '{print $1}')

if [ -n "$EM_RUN" ]; then
  echo "container $EM_RUN is running.will stop and delete it."
  docker stop "$EM_RUN"
  docker rm "$EM_RUN"
elif [ -n "$EM" ]; then
  echo "container $EM is stop,but container is exists,will only delete it."
  docker rm "$EM"
else
  echo "Not find container $SERVER_NAME"
fi

echo "run new container"

docker run --name $SERVER_NAME -d \
-p $PORT:$PORT \
-v $DIR/data:/var/lib/mysql \
-v $DIR/logs:/var/log/mysql \
-e MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD \
-e TZ=Asia/Shanghai \
--restart=always $IMAGE_NAME:$VERSION \
--character-set-server=utf8mb4 \
--collation-server=utf8mb4_general_ci
